//
//  HMEmoticonKeyboard.swift
//  表情键盘
//
//  Created by Apple on 16/7/28.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

/// 自定义的表情键盘
class HMEmoticonKeyboard: UIView {
    weak var textView: UITextView?
    
    private let ReuseIdentifier = "ReuseIdentifier"
    
    /// collectionView的布局
    private let layout = UICollectionViewFlowLayout()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        // 自己来指定frame
        let newFrame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 216)
        
        super.init(frame: newFrame)
        
        backgroundColor = UIColor.brownColor()
        setupUI()
    }
    
    /// 设置UI
    private func setupUI() {
        // 添加控件
        self.addSubview(collectionView)
        self.addSubview(emoticonToolBar)
        self.addSubview(pageControl)
        
        // 添加约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        emoticonToolBar.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        
        // VFL
        /* 
            format: String: ||: 父控件的边界
                H: 水平方向 || 父控件左边和父控件右边
                V: 垂直方向 || 父控件顶部和父控件底部
                []: 要约束的view
        */
        self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView]))
        self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : emoticonToolBar]))
        
        self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(==44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView, "tb": emoticonToolBar]))
        
        // pageControl
        self.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 25))
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // collectionView的frame是有值
        // 一个cell就和collectionView一样大
        self.layout.itemSize = self.collectionView.frame.size
        
    }
    
    // MARK: - 懒加载
    /// collectionView
    private lazy var collectionView: UICollectionView = {
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
        
        // 水平滚动
        self.layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        self.layout.minimumInteritemSpacing = 0
        self.layout.minimumLineSpacing = 0
        
        cv.showsHorizontalScrollIndicator = false
        cv.pagingEnabled = true
        cv.bounces = false
        
        cv.dataSource = self
        cv.delegate = self
        
        cv.registerClass(HMEmoticonCell.self, forCellWithReuseIdentifier: self.ReuseIdentifier)
        
        return cv
    }()
    
    /// toolBar
    private lazy var emoticonToolBar: HMEmoticonToolBar = {
        let toolBar = HMEmoticonToolBar()
        
        toolBar.delegate = self
        
        return toolBar
    }()
    
    /// pageControl
    private lazy var pageControl: UIPageControl = {
        let pc = UIPageControl()
        
        // 设置
        pc.numberOfPages = 6
        pc.currentPage = 3
        
        
        // 设置图片, 使用图片平铺成颜色
//        pc.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
//        pc.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        
        /*
        name: Optional("_currentPageImage"), type: Optional("@\"UIImage\"")
        name: Optional("_pageImage"), type: Optional("@\"UIImage\"")
        */
        // 私有成员变量不能直接赋值,KVC
        pc.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "currentPageImage")
        pc.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "pageImage")
        
        pc.hidden = true
        
        return pc
    }()
}

extension HMEmoticonKeyboard: HMEmoticonToolBarDelegate {
    /// toolBar点击了一个按钮
    func emoticonToolBar(didSelectedType type: EmoticonToolBarType) {
        print("我在键盘里面知道按钮点击了: \(type)")
        // collectionView滚动到对应的位置
        let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
        
        // 选中collectionView的某个cell
        collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.Left)
        
        // 设置pageControl
        setupPageControl(indexPath)
    }
}

extension HMEmoticonKeyboard: UICollectionViewDataSource, UICollectionViewDelegate {
    // 返回多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // 返回所有表情包
        return HMEMoticonManager.sharedManager.emoticonPackages.count
    }
    
    // 某组返回多少个cell
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 获取某组表情页数
        // HMEMoticonManager.sharedManager.emoticonPackages[section]: 获取对应的表情包
        // allPageEmoticons.count: 获取表情包里面的页数
        return HMEMoticonManager.sharedManager.emoticonPackages[section].allPageEmoticons.count
    }
    
    // 返回cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! HMEmoticonCell
        
        // 设置代理
        cell.delegate = self
        
        cell.indexPath = indexPath
        
        // 将cell对应这页的模型赋值
        // 获取表情包模型
        // 从表情包里面获取到对应页的数据
        let emotiocnPackage = HMEMoticonManager.sharedManager.emoticonPackages[indexPath.section]
        cell.pageEmoticons = emotiocnPackage.allPageEmoticons[indexPath.item]
        
        return cell
    }
    
    // scrollView滚动
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 计算跑到哪一组了
        // 看哪个cell在collectionView中占的位置多,看哪个cell的frame包含中心点
        var refPoint = collectionView.center
        
        // 参照点和frame的起始点要是同一个点
        refPoint.x += scrollView.contentOffset.x
        
//        print("参照点: \(refPoint)")
        
        // 获取正在显示的cell
        for cell in collectionView.visibleCells() {
            // 获取每个正在显示的cell,看哪个cell的frame包含中心点
            if cell.frame.contains(refPoint) {
                // 这个cell包含中心点.让toolBar里面的按钮选中cell所在的组
                let indexPath = collectionView.indexPathForCell(cell)
//                print("我要选中: \(indexPath!.section)")
                emoticonToolBar.switchSelectedButton(indexPath!.section)
                
                setupPageControl(indexPath!)
            }
        }
    }
    
    private func setupPageControl(indexPath: NSIndexPath) {
        // 设置pageControl
        pageControl.numberOfPages = HMEMoticonManager.sharedManager.emoticonPackages[indexPath.section].allPageEmoticons.count
        pageControl.currentPage = indexPath.item
        
        // 如果只有一页就不显示
        pageControl.hidden = (HMEMoticonManager.sharedManager.emoticonPackages[indexPath.section].allPageEmoticons.count == 1)
    }
}

extension HMEmoticonKeyboard: HMEmoticonCellDelegate {
    // 一个表情按钮被点击时调用
    func emoticonCellDidClick(emoticonModel model: HMEmoticonModel) {
        // 将内容添加到textView上面去
        textView?.insertEmoticon(model)
        
        // 添加到最近这组里面
        HMEMoticonManager.sharedManager.addFavorite(model)
    }
    
    // cell删除按钮被点击了
    func emoticonCellDidClickDeleteButton() {
        // 去textView上面删除光标前面的内容
        textView?.deleteBackward()
    }
}